package com.ujiuye.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      //1.获取文件名(用户想下载的资源名称)
        String fileName = req.getParameter("fileName");
        //设置浏览器的响应头  告知浏览器以附件下载形式打开
        //该资源 URLEncoder.encode(文件名,"utf-8")
        resp.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName,"utf-8"));
        String path = getServletContext().getRealPath("/img/" + fileName);
        FileInputStream fis = new FileInputStream(path);
        byte[] arr = new byte[1024*8];
        int len;
        //获取响应流
        ServletOutputStream fos = resp.getOutputStream();
        while ((len=fis.read(arr))!=-1){
            fos.write(arr,0,len);
        }
        fos.close();
        fis.close();
    }
}
